package com.zhugang.week03;

/**
 * @program algorithms
 * @description: circularQueue, 会浪费一个空间（不需要搬移数据）
 * @author: chanzhugang
 * @create: 2022/06/02 15:49
 */
public class CircularQueue {

    private final String[] items;
    private final int n;
    private int head;
    private int tail;

    public CircularQueue(int capacity) {
        this.n = capacity;
        this.items = new String[capacity];
    }

    /**
     * 入队
     *
     * @param item
     * @return
     */
    public boolean enqueue(String item) {
        // 循环队列满： (tail + 1) % n == head; 会浪费一个空间
        if ((tail + 1) % n == head) return false;
        items[tail] = item;
        tail = (tail + 1) % n;
        return true;
    }

    /**
     * 出队
     *
     * @return
     */
    public String dequeue() {
        // head == tail，队列为空
        if (head == tail) return null;
        String item = items[head];
        head = (head + 1) % n;
        return item;
    }
}
